import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Modal, Button, Form, message, Row, Col, Upload } from 'antd';
import PropTypes from 'prop-types';
import { getToken } from '@/utils/utils';
import { fromJS } from 'immutable';
import DetailModal from './exportDetailModel';
import { exportExlsx } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common';

const mapStateToProps = (state: any) => ({
  ControlBoxMng: state.ControlBoxMng,
});
class ExportModal extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      fileList: [],
      detailVisible: false,
      cboxList: [], //存储校验后的手持机list信息
      showErr: false,
    };
  }

  //批量保存
  handleSubmit = () => {
    const { cboxList, fileList } = this.state;
    if(!fileList.length)return message.warning('未导入数据，无法确定保存！');
    if(!cboxList.length)return message.warning('导入数据为空，无法确定保存！');
    for (let i = 0; i < cboxList.length; i++) {
      if (cboxList[i].result !== 0) {
        message.warning('导入数据有误，无法确定保存！');
        return;
      } else {
        continue;
      }
    }
    this.batchSave();
  };
  batchSave = () => {
    const { dispatch } = this.props;
    const { cboxList } = this.state;
    this.setState({
      loading: true,
    });
    const list = cboxList;

    dispatch({
      type: 'ControlBoxMng/postListList',
      payload: {
        url: '/msalcohollock/cbox/batch',
        list,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('批量保存成功');
          this.close();
          dispatch({
            type: 'ControlBoxMng/getFetchPage',
            payload: {
              url: '/msalcohollock/cbox/page',
            },
          });
        }
        this.setState({
          loading: false,
        });
      },
    });
  };
  close = () => {
    const { closeModal } = this.props;
    this.setState({
      fileList: [],
      cboxList: [],
      showErr: false,
    });
    closeModal();
  };
  removeList = (fileList: any, file: any) => {
    const newList = fromJS(fileList).toJS();
    const i = newList.findIndex(e => e.uid === file.uid);
    if (i >= 0) {
      newList.splice(i, 1);
    }
    return newList;
  };
  // 文件删除
  handleRemove = (file: any) => {
    const { fileList } = this.state;
    const newList = this.removeList(fileList, file);
    this.setState({ fileList: newList });
  };
  // 文件上传前校验
  beforeFileUpload = (file: any) => {
    const { fileList } = this.state;
    const isXlsx = file.name.endsWith('.xlsx');
    if (!isXlsx) {
      message.error('请上传.xlsx格式文件');
      return false;
    }

    if (fileList.length === 1) {
      message.warning('只能上传一个文件！');
      return false;
    }
    return true;
  };
  handleChange = (info: any) => {
    const { fileList, file } = info;
    const newList = this.removeList(fileList, file);

    if (
      file.status === 'done' &&
      file.response &&
      file.response.statusCode === '0' &&
      file.response.data
    ) {
      message.success(`${file.name} 上传成功`);
      this.setState({
        cboxList: file.response.data?.checkList??[],
        showErr: Number(file.response.data?.checkResult) !== 0,
      });
    } else if (file.status === 'done' && file.response && Number(file.response.statusCode) !== 0) {
      if (file.response.data) {
        message.error(file.response.data + '在' + file.response.statusMessage);
      } else {
        message.error(file.response.statusMessage);
      }
      this.setState({ fileList: [] });
      // this.setState({ fileList: newList });
      return;
    } else if (file.status === 'removed') {
      this.setState({
        showErr: false,
        cboxList: [],
      });
      message.success('删除成功');
      return;
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
      this.setState({ fileList: newList });
      return;
    } else if (!file.status) {
      this.setState({ fileList: newList });
      return;
    }
    this.setState({ fileList });
  };
  handleDetail = () => {
    this.setState({ detailVisible: true });
  };
  closeModal = () => {
    this.setState({ detailVisible: false });
  };
  exportTable = () => {
    exportExlsx({
      table: [['控制盒编号（必填）', '控制盒名称'], ['controlBox001', '测试控制盒001']],
      name: '控制盒批量上传模板'
    });
  };
  render() {
    const { loading, detailVisible, cboxList, showErr } = this.state;
    const { modalVisible } = this.props;
    const domain = window.g.url;
    const uploadUrl = '/msalcohollock/cbox/batch/check';
    const uploadStr = `${domain}${uploadUrl}`;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
          确定
        </Button>
      </div>
    );
    
    const props = {
      action: uploadStr,
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders() },
      multiple: false,
      accept: '.xls,.xlsx,application/vnd.ms-excel',
      onRemove: this.handleRemove,
      beforeUpload: this.beforeFileUpload,
      onChange: this.handleChange,
    };
    return (
      <Modal
        title={'批量导入'}
        footer={footer}
        visible={modalVisible}
        width={700}
        onCancel={this.close}
      >
        <Row gutter={24}>
          <Col span={16}>
            <Form>
              <Form.Item label="批量导入控制盒">
                <Upload {...props} fileList={this.state.fileList}>
                  <Button type="primary" style={{ width: '200px' }}>
                    点击上传
                  </Button>
                </Upload>
                <div style={{ fontSize: 12, color: 'grey', width: '200px' }}>
                  只能上传xls,xlsx格式的Excel文件
                </div>
                {showErr ? <div style={{ fontSize: 12, color: 'red' }}>导入数据有误</div> : null}
              </Form.Item>
            </Form>
          </Col>
          <Col span={4}>
            <Button type="primary" shape="round" onClick={this.exportTable}>
              下载模板
            </Button>
          </Col>
          <Col span={4}>
            <Button
              type="primary"
              shape="round"
              onClick={() => {
                this.handleDetail();
              }}
            >
              导入详情
            </Button>
          </Col>
        </Row>
        <DetailModal
          cboxList={cboxList}
          modalVisible={detailVisible}
          closeModal={this.closeModal}
        ></DetailModal>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(ExportModal);
